from fastapi import APIRouter,Request,Response
from fastapi.responses import JSONResponse
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel
from redis.asyncio import Redis
import json
from app.plugins.RsaEncrypt import decrypt_data
from app.plugins.AesEncrypt import AESencrypt
from app.plugins.SHA1 import sha1_encrypt
import os,sys
register_router = APIRouter()
BASE_DIR = os.path.dirname(os.path.realpath(sys.argv[0]))
path = os.path.join(BASE_DIR, 'app/templates')
templates = Jinja2Templates(directory=path)

@register_router.get("/register")
def get_register(request:Request):
    return templates.TemplateResponse("register.html", {"request": request})

@register_router.post("/register/checkUserName")
async def checkUserName(request:Request,data:dict):
    async with Redis.from_url(url="redis://localhost:6379/0",decode_responses=True) as redis:
        userset = await redis.smembers('userinfo')
        userlist = [json.loads(item) for item in list(userset)]
    username = data['username']
    for item in userlist:
        if item['name'] == username:
            return JSONResponse(content={"message": "用户名已存在"},status_code=400)
    return JSONResponse(content={"message": "用户名可用"},status_code=200)

@register_router.get("/register/getPublicKey")
def get_publickey(request:Request):
    # 获取公钥,避免每次公钥都是这个，对公钥进行aes加密
    t = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC43IyaUKumw59Dtz0bJfWqkzjMJOkxJNwMc2QTKF4LqUS7rUnaJQXTUkynL4KcM6f20HcAVckOd4FBuw3UcetCjCQu1J1SWUYxGvLwFD+yrbj/XOqQ8M3h3hX8/CS74EzwifvXB/c/EJ/pDCeWQZhcRzKNyu5Nox1Qo/dk8bKZ6wIDAQAB'
    public_key=AESencrypt(t)
    return JSONResponse({"public_key": public_key},status_code=200)


@register_router.post("/register/toRegister")
async def toRegister(request: Request,data:dict):
    username = data['username']
    password = data['password']
    password = decrypt_data(password)
    #对password进行sha1加密
    password = sha1_encrypt(password)
    async with Redis.from_url(url="redis://localhost:6379/0",decode_responses=True) as redis:
        await redis.sadd('userinfo',json.dumps({'name':username,'password':password}))
    return JSONResponse(content={"message": "注册成功"},status_code=200)